import { useEffect, useState, useMemo, Fragment } from "react";
import * as api from "@/api/product";
import { Table, Image, Button, Modal, message, DatePicker } from "antd";
import {
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import "./index.css";
import Dialog from "@/components/Dialog";

const ProductCategory = () => {
  let [category, setCategory] = useState([]);
  let [open, setOpen] = useState(false);
  let [loading, setLoading] = useState(true);

  //获取类目数据方法抽离
  let getCategory = () => {
    api.getCategory().then((res) => {
      if (res.data.status === 200) {
        setCategory([...res.data.data]);
        setLoading(false);
      }
    });
  };

  useEffect(() => {
    getCategory();
  }, []);

  let dataSource = useMemo(() => {
    return category.map((item) => ({
      cId: item.category_id,
      cImg: item.categoryImgurl,
      cName: item.categoryName,
      creator: item.creator,
      cCTime: item.createTime,
      cUpdator: item.updator,
      cUpdateTime: item.updateTime,
      key: item._id,
    }));
  }, [category]);
  //   console.log("dataSource", dataSource);

  let titles = [
    "类目id",
    "类目图片",
    "类目名称",
    "创建人",
    "创建时间",
    "更新人",
    "更新时间",
  ];

  //批量删除准备
  let checkedArray = [];
  //批量删除选中处理
  const handleCheckbox = (e, td) => {
    if (e.target.checked) {
      if (!checkedArray.includes(td)) {
        checkedArray.push(td);
      }
    } else {
      let Index = checkedArray.findIndex((item) => item === td);
      checkedArray.splice(Index, 1);
    }
  };
  //准备cloumns 6项的每一项 工作 的定义  采集数据的 引导
  let cloumns = useMemo(() => {
    // 劫持一下表格数组  push 操作列
    let col = [];
    try {
      // 先获取 dataSource 中item 的键 做 标准键
      let dataSourceItemKeys = Object.keys(dataSource[0]); //['cImg','cId','cName','creator','cCTime','cUpdator','cUpdateTime','key']
      // 定义了 6个 表头  生成6个 表头采集数据 的引导
      //根据 titles 的数量 生产 对应得数据 用到 dataSource item数据对象中的键
      col = titles.map((title, index) => {
        if (dataSourceItemKeys[index] === "cId") {
          return {
            title,
            key: dataSourceItemKeys[index],
            dataIndex: dataSourceItemKeys[index],
            align: "center",
            render: (td, tr) => (
              <Fragment>
                <input
                  type="checkbox"
                  onChange={(e) => handleCheckbox(e, td)}
                />
                <span>{td}</span>
              </Fragment>
            ),
          };
        } else if (dataSourceItemKeys[index] === "cImg") {
          return {
            title,
            key: dataSourceItemKeys[index],
            dataIndex: dataSourceItemKeys[index],
            align: "center",
            width: 120,
            render: (v, r) => (
              <Image
                width={110}
                src={v}
                fallback="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            ),
          };
        } else {
          return {
            title,
            key: dataSourceItemKeys[index],
            dataIndex: dataSourceItemKeys[index],
            align: "center",
          };
        }
      });

      // 增加 列 数据头
      let lastColumnObj = {
        title: "操作",
        key: "operate",
        align: "center",
        width: 320,
        render: (_, rowData) => (
          <Fragment>
            <Button
              icon={<EyeOutlined />}
              style={{ backgroundColor: "green" }}
              type="primary"
              onClick={() => handleVivew(rowData)}
            >
              {/* 查看 */}
            </Button>
            <Button
              icon={<EditOutlined />}
              style={{ margin: "0 10px" }}
              type="primary"
              onClick={() => handleUpdateCategory(rowData)}
            >
              {/* 编辑 */}
            </Button>
            <Button
              danger
              icon={<DeleteOutlined />}
              type="primary"
              onClick={() => handleDeleteCategory(rowData)}
            >
              {/* 删除 */}
            </Button>
          </Fragment>
        ),
      };

      col.push(lastColumnObj);
      return col;
    } catch (e) {
      //   console.log(e);
    }
  }, [category]);
  //   console.log("cloumns", cloumns);

  //
  const handleVivew = (rowData) => {
    Modal.info({
      title: "类目信息展示",
      icon: "",
      content: (
        <Fragment>
          <h3>类目名称：{rowData.cName}</h3>
          <p>创建人：{rowData.creator}</p>
          <p>创建时间：{rowData.cCTime}</p>
          <Image width={200} src={rowData.cImg} />
        </Fragment>
      ),
      okText: "确认",
    });
  };

  //删除数据
  const handleDeleteCategory = (rowData) => {
    // console.log(rowData);
    Modal.confirm({
      title: "确认删除?",
      icon: <ExclamationCircleOutlined />,
      content: (
        <Fragment>
          <h3>类目名称：{rowData.cName}</h3>
          <p>创建人：{rowData.creator}</p>
          <p>创建时间：{rowData.cCTime}</p>
        </Fragment>
      ),
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        api.delCategory(rowData.cId).then((res) => {
          //   console.log(res);
          message.success("删除成功");
          getCategory();
        });
      },
      onCancel: () => {
        message.info("已取消删除");
      },
    });
  };

  let [dialogDataShow, setDialogDataShow] = useState({});
  let [category_id, setCategory_id] = useState();
  //修改类目
  const handleUpdateCategory = (rowData) => {
    setOpen(true);
    setDialogDataShow({
      categoryName: rowData.cName,
      categoryImgurl: rowData.cImg,
    });
    setCategory_id(rowData.cId);
  };

  /*  let cloumns = useMemo(()=>{
    {
        title:'类目图片',
        key:"cImg",
        dataIndex:"cImg",
    }
  },[category]) */

  //   let cloumns = [
  //     {
  //       title: "类目图片",
  //       key: "cImg",
  //       dataIndex: "cImg",
  //     },
  //     {
  //       title: "类目id",
  //       key: "cId",
  //       dataIndex: "cId",
  //     },
  //   ];

  //dialog 提交按钮 处理
  const handleOk = (FormInstance) => {
    FormInstance.submit();
    setOpen(false);
  };

  const handleCancel = () => {
    setOpen(false);
    setIsAddCategory(false);
  };

  let [isAddCategory, setIsAddCategory] = useState(false);
  // 页面增加按钮 处理
  const handleAdd = () => {
    // console.log("isAddCategory", isAddCategory);
    setIsAddCategory(true);
    setOpen(true);
  };

  //批量删除
  const massDelete = () => {
    message.loading("删除中。。");
    api.delCategory(checkedArray).then((res) => {
      if (res.data.state) {
        message.success(res.data.msg);
      }
    });
  };

  //
  const onChange = (date, dateString) => {
    console.log(date, dateString);
  };
  return (
    <Fragment>
      <Dialog
        onOk={handleOk}
        onCancel={handleCancel}
        open={open}
        setOpen={setOpen}
        getCategory={getCategory}
        dialogDataShow={dialogDataShow}
        setDialogDataShow={setDialogDataShow}
        category_id={category_id}
        isAddCategory={isAddCategory}
        setIsAddCategory={setIsAddCategory}
      />
      <div
        id="search"
        style={{
          height: 42,
        }}
      >
        <label htmlFor="a">产品名称</label>
        <input type="text" id="a" placeholder="输入产品名称" />
        <label htmlFor="date">添加时间</label>
        <DatePicker onChange={onChange} id="date" placeholder="请选择时间" />
        <Button icon={<SearchOutlined />} type="primary">
          查询
        </Button>
      </div>
      <div
        id="addProduct"
        style={{
          height: 60,
          border: "1px solid #ccc",
          padding: "13px 15px",
          marginBottom: 15,
        }}
      >
        <Button
          icon={<PlusOutlined />}
          style={{
            backgroundColor: "orange",
            color: "#fff",
            borderRadius: 5,
          }}
          onClick={handleAdd}
        >
          增加商品
        </Button>
        <Button
          icon={<DeleteOutlined />}
          style={{
            backgroundColor: "rgb(255,81,87)",
            color: "#fff",
            marginLeft: 10,
            borderRadius: 5,
          }}
          onClick={massDelete}
        >
          批量删除
        </Button>
      </div>
      <Table
        loading={loading}
        bordered
        columns={cloumns}
        dataSource={dataSource.reverse()}
      />
    </Fragment>
  );
};

export default ProductCategory;
